<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :sm="24" :lg="6" style="padding-left: 20px">
        <!--        card1-->
        <el-card class="up-card">
          <template v-slot:header>
            <div class="clearfix">
              <span>总览</span>
            </div>
          </template>
          <div class="body">
            <el-statistic title="接入电网的家庭" :value="total" :formatter="(value)=>{
              return value+'kwh'
            }">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  今日发电总量
                  <el-tooltip
                      effect="dark"
                      content="今日所有的风场发电总额"
                      placement="top"
                  >
                    <el-icon style="margin-left: 4px" :size="12">
                      <Warning/>
                    </el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>

      <!--      card2-->
      <el-col :sm="24" :lg="6" style="padding-left: 10px">
        <el-card class="up-card">
          <template v-slot:header>
            <div class="clearfix">
              <span>设备状态</span>
            </div>
          </template>
          <div class="body">
            <el-statistic title="所有风场内总计的风电设备在线数" v-bind:value="total" :formatter="(value) => {
              return farmDevice.workingDevicesCount+'/'+farmDevice.totalDevicesCount+'台'
            }">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  在线的设备数
                  <el-tooltip
                      effect="dark"
                      content="所有风场内总计的风电设备在线数"
                      placement="top"
                  >
                    <el-icon style="margin-left: 4px" :size="12">
                      <Warning/>
                    </el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>


      <!--      card3-->
      <el-col :sm="24" :lg="6" style="padding-left: 10px">
        <el-card class="up-card">
          <template v-slot:header>
            <div class="clearfix">
              <span>告警信息</span>
            </div>
          </template>
          <div class="body">
            <el-statistic v-bind:value="faultCount">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  待处理的告警信息
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>


      <!--      card4-->
      <el-col :sm="24" :lg="6" style="padding-left: 10px;padding-right: 20px">
        <el-card class="up-card">
          <template v-slot:header>
            <div class="clearfix">
              <span>上班人数</span>
            </div>
          </template>
          <div class="body">
            <el-statistic v-bind:value="totalMember">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  现有上班人数
                  <el-tooltip
                      effect="dark"
                      content="还有人陪你上班"
                      placement="top"
                  >
                    <el-icon style="margin-left: 4px" :size="12">
                      <Warning/>
                    </el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-divider/>

    <el-container>
      <el-main>
        <el-row :gutter="20">

          <el-col :xs="24" :sm="24" :md="12" :lg="12">
            <el-card class="chart-card">
              <template v-slot:header>
                <div class="clearfix">
                  <span>风力图</span>
                </div>
              </template>
              <div class="body">
                <v-chart class="upChart" :option="windOption" autoresize/>
              </div>
            </el-card>
          </el-col>


          <el-col :xs="24" :sm="24" :md="12" :lg="12">
            <el-card class="update-log">
              <template v-slot:header>
                <div class="clearfix">
                  <span>电力图</span>
                </div>
              </template>
              <div class="body">
                <v-chart class="upChart" :option="eleOption" autoresize/>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="24">
            <el-card class="update-log">
              <template v-slot:header>
                <div class="clearfix">
                  <span>在线设备数</span>
                </div>
              </template>
              <div class="body">
                <v-chart class="upChart" :option="DeviceOption" autoresize/>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>

      <el-aside width="23.5%" style="padding: 0;margin-right: 10px">
        <el-card class="aside-card">
          <template v-slot:header>
            <div class="clearfix">
              <span>各大运营商设备数量</span>
            </div>
          </template>
          <div class="body">
            <ul>
              <li v-for="item in operator"><span><dict-tag :options="farm_operators" :value="item.name"
                                                           style="float: left"/>:{{ item.count }}</span>
                <el-divider/>
              </li>

            </ul>
          </div>
        </el-card>
      </el-aside>
    </el-container>

  </div>
</template>

<script setup>
import { Warning } from "@element-plus/icons-vue";
import { list as initOnline } from "@/api/monitor/online";
import { listFault_record as initFault } from "@/api/fault_record/fault_record.js";
import {getFarmByDeptId, listFarm} from "@/api/farm_manage/farm.js";
import { ref, reactive } from "vue";
import useUserStore from '@/store/modules/user';
import { listUser } from "@/api/system/user.js";

const { proxy } = getCurrentInstance();
const { farm_operators } = proxy.useDict('farm_operators');

// 状态管理
const onlineList = reactive([]);
const totalMember = ref(0);
const faultCount = ref(0);
const faultList = reactive([]);
const dept = ref(null);
const userId = useUserStore().id;
const userList = ref([]);
const farmList = ref([]); // 存储风场数据
const farmDevice = ref({
  totalDevicesCount: 0,
  workingDevicesCount: 0
});
const operator = ref([]); // 运营商设备数量列表
const onlineDeviceList = ref([]); // 在线设备历史数据

/**
 * 初始化数据加载
 */
async function init() {
  try {
    // 并行加载基础数据
    const [onlineRes, faultRes, userRes] = await Promise.all([
      initOnline(),
      initFault(),
      listUser()
    ]);

    // 设置在线用户数据
    onlineList.value = onlineRes.rows;
    totalMember.value = onlineRes.total;

    // 设置故障数据
    faultList.value = faultRes.rows;
    faultCount.value = faultList.value.filter(item => item.status == 2).length;

    // 处理用户数据
    userList.value = userRes.rows;
    const currentUser = userList.value.find(user => user.userId === userId);

    if (currentUser) {
      dept.value = currentUser.deptId;
      await loadFarmData();

      // 初始化在线设备历史数据（前9次）
      for (let i = 0; i < 9; i++) {
        onlineDeviceList.value.push(farmDevice.value.workingDevicesCount);
      }
    }
  } catch (error) {
    console.error('初始化数据加载失败:', error);
  }
  console.log(dept.value);
}

/**
 * 加载并更新风场数据
 */
async function loadFarmData() {
  try {
    const response = await listFarm();
    farmList.value = response.rows;

    // 重置统计
    farmDevice.value = {
      totalDevicesCount: 0,
      workingDevicesCount: 0
    };
    operator.value = [];

    // 计算统计信息
    farmList.value.forEach(farm => {
      farmDevice.value.totalDevicesCount += farm.totalDevicesCount;
      farmDevice.value.workingDevicesCount += farm.workingDevicesCount;
      operator.value.push({
        name: farm.operator,
        count: farm.totalDevicesCount
      });
    });
  } catch (error) {
    console.error('加载风场数据失败:', error);
  }
}

// 随机生成数据的函数（0-50 的随机数）
const generateRandomData = () => Array.from({ length: 7 }, () => Math.floor(Math.random() * 50));

// 获取最近时间标签（格式：HH:mm:ss）
const getRecentTimeLabels = (count = 7) => {
  const now = new Date();
  return Array.from({ length: count }, (_, i) => {
    const timePoint = new Date(now.getTime() - (count - i - 1) * 5000);
    return `${timePoint.getHours().toString().padStart(2, '0')}:${timePoint.getMinutes().toString().padStart(2, '0')}:${timePoint.getSeconds().toString().padStart(2, '0')}`;
  });
};

// 初始化 windOption 图表配置
const windOption = ref({
  xAxis: {
    type: 'category',
    data: getRecentTimeLabels()
  },
  yAxis: { type: 'value' },
  series: [{
    data: generateRandomData(),
    type: 'bar'
  }]
});

// 初始化 eleOption 图表配置
const eleOption = ref({
  xAxis: {
    type: 'category',
    data: getRecentTimeLabels()
  },
  yAxis: { type: 'value' },
  series: [{
    data: generateRandomData(),
    type: 'bar'
  }]
});

// 初始化 DeviceOption 图表配置
const DeviceOption = ref({
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: getRecentTimeLabels()
  },
  yAxis: { type: 'value' },
  series: [{
    data: onlineDeviceList.value,
    type: 'line',
    areaStyle: {}
  }]
});

/**
 * 定时更新数据
 */
const intervalUpdate = async () => {
  try {
    // 更新图表数据
    const newData = generateRandomData();
    windOption.value.series[0].data = newData;
    windOption.value.xAxis.data = getRecentTimeLabels();

    eleOption.value.series[0].data = newData;
    eleOption.value.xAxis.data = getRecentTimeLabels();

    DeviceOption.value.xAxis.data = getRecentTimeLabels();

    // 重新加载风场数据
    await loadFarmData();

    // 更新在线设备历史数据
    onlineDeviceList.value.push(farmDevice.value.workingDevicesCount);

    // 保持最多10条记录
    if (onlineDeviceList.value.length > 10) {
      onlineDeviceList.value.shift();
    }

    // 更新设备图表
    DeviceOption.value.series[0].data = onlineDeviceList.value;
  } catch (error) {
    console.error('定时更新数据失败:', error);
  }
};

// 定时器管理
let updateInterval = null;

onMounted(() => {
  updateInterval = setInterval(intervalUpdate, 5000);
});

onUnmounted(() => {
  if (updateInterval) {
    clearInterval(updateInterval);
    updateInterval = null;
  }
});

// 初始化执行
init();
intervalUpdate();
</script>

<style scoped lang="scss">
.clearfix {
  font-size: 20px;
}

.upChart {
  height: 260px;
}

.el-row {
  margin-bottom: 10px;
}

.aside-card {
  height: 100%;
}


</style>
